package com.financing.platform.web.api;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.financing.platform.dto.*;
import com.financing.platform.service.IFaNoticeService;
import com.financing.platform.util.Constants;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.service.IOrderPhoService;
import com.financing.platform.service.IOrderService;
import com.financing.platform.service.IOrderTmpService;
import com.financing.platform.service.IProductOrderDataService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.Dict;
import com.financing.platform.vo.OrderPhoVO;

@Controller
@RequestMapping("/api/orderpho")
@Scope("prototype")
public class OrderPhoAction  extends BaseAction{
	
	@Autowired
	IOrderPhoService orderPhoService;
	
	@Autowired
	IOrderService orderService;
	
	@Autowired
	IOrderTmpService orderTmpService;
	
	@Autowired 
	IProductOrderDataService productOrderDataService;

	@Autowired
	IOrderPhoService orderPhoServiceImpl;
	@Autowired
	private IFaNoticeService faNoticeService;
	@Value("#{settings['fileBaseDir']}")
	private String fileBaseDir;
	
	@RequestMapping("/orderPhoDetail.shtml")
	@ResponseBody
	public ResultMap orderPhoDetail(HttpServletRequest request,
			HttpServletResponse response,OrderPhoVO orderPhoVO) {
		try{
			List<Map<String, Object>> queryOrderPho = orderPhoService.queryOrderPho(orderPhoVO);

			OrderByGaiZaoDTO orderByGaiZaoDTO =  new OrderByGaiZaoDTO();
			orderByGaiZaoDTO.setId(orderPhoVO.getoId());
			OrderByGaiZaoDTO queryOrderResult = orderService.queryOrderDetailByGaiZao(orderByGaiZaoDTO);
			resultMap.setAttribute("list", queryOrderPho);
			resultMap.setAttribute("oLocation", queryOrderResult == null ? null: queryOrderResult.getoLocation());
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("query proOrderDataDetail error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	@RequestMapping("/updateOrderPho.shtml")
	@ResponseBody
	public ResultMap updateOrderPho(HttpServletRequest request,
			HttpServletResponse response,OrderPhoVO orderPhoVO) {
		try{
			String updateBy ="system";
			HttpSession session=request.getSession();
			if(null != session && null != session.getAttribute("USER")){
				UserInfoDTO userinfo = (UserInfoDTO) session.getAttribute("USER");
				updateBy = userinfo.getUsername();
			}else{
				resultMap.setStatus(STATUS.NEED_LOGIN);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_ONLOGIN);
				return resultMap;
			}
			orderPhoVO.setUpdateBy(updateBy);


			//判断是否  退回发送消息
			OrderPhoVO querBean = orderPhoService.queryOrderPhoById(orderPhoVO.getId());
			if(orderPhoVO.getoPhoStatus().equals("04") && queryOrderPhoStatus(querBean)){

				//成功 交易通知  订单流程改造后，交易通知入库 start----
				FaNoticeDTO notice = new FaNoticeDTO();
				DTOdateSet.setCreateInfo(notice, request.getSession());
				DTOdateSet.setUpdateInfo(notice, request.getSession());
				notice.setOrderId(querBean.getoId());
				faNoticeService.addFaPhoNotice(notice);
				// 订单流程改造后，交易通知入库 end----

			}

			int i=orderPhoService.updateOrderPho(orderPhoVO);
			resultMap.setStatus(i>0?STATUS.SUCCESS:STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("updateOrderPho error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	private Boolean queryOrderPhoStatus(OrderPhoVO querBean) throws Exception {

		if(querBean == null ){
			return  false;
		}
		Boolean phoStatus = false;

		//获取 三件套 状态

		OrderPhoVO queryOrderPhoVO = new OrderPhoVO();
		// 查询订单是否上传了资料
		queryOrderPhoVO.setoId(querBean.getoId().toString());
		queryOrderPhoVO.setpId(querBean.getpId().toString());
		queryOrderPhoVO.setpType(querBean.getpType());
		List<Map<String, Object>> queryOrderPho = orderPhoServiceImpl.queryOrderPho(queryOrderPhoVO);


		Map<String,String> map = new HashMap<String,String>();
		for(Map<String, Object> phoMap: queryOrderPho){
            if( phoMap == null || phoMap.get("oPhoStatus") == null){
                map.put("01", "01");
                continue;
            }
            map.put(phoMap.get("oPhoStatus").toString(), "01");
        }

		if(map.containsKey(Constants.order_data_pho_rev_no)){
			phoStatus = true;

        }else if(map.containsKey(Constants.order_data_pho_rev_fail)){
            phoStatus = false;

        }else if(map.containsKey(Constants.order_data_pho_rev_yes) ){
            phoStatus = true;

        }else if(map.containsKey(Constants.order_data_pho_rev_success) && !map.containsKey(Constants.order_data_pho_rev_yes)){
            phoStatus = true;

        }else{
            //默认
			phoStatus = true;
        }
        return phoStatus;
	}

	@RequestMapping("/addOrderPhoData.shtml")
	@ResponseBody
	public ResultMap addOrderPhoData(HttpServletRequest request,
			HttpServletResponse response,OrderPhoVO orderPhoVO) {
		try{
			
			HttpSession session=request.getSession();
			DTOdateSet.setUpdateInfo(orderPhoVO,session);
			orderPhoVO.setCreateBy(orderPhoVO.getUpdateBy());
			orderPhoVO.setUpdateBy(orderPhoVO.getUpdateBy());
			
			OrderDTO  od=new OrderDTO();
			od.setId(orderPhoVO.getoId());
			OrderDTO orderDTO =  orderService.queryOrderDetail(od);
			if(orderDTO == null){
				//非私募 没有  查询私募订单
				List<OrderTmpDTO> queryInfoByOrderTmpIds = orderTmpService.queryInfoByOrderTmpIds(orderPhoVO.getoId());
				if(queryInfoByOrderTmpIds.size()==0){
					resultMap.setStatus(STATUS.ERROR);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
					resultMap.setMessage("OrderDTO is not exists");
					return resultMap;
				}
			}
			
			UserInfoDTO userinfo = (UserInfoDTO)session.getAttribute("USER");
			String orderPhos=request.getParameter("orderPhos")+" ,";
			String orderPhosStatus=request.getParameter("orderPhosStatus")+" ,";
			
			addOrderPhos(orderPhoVO, userinfo, orderPhos,orderPhosStatus);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryProductOrderData error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	@RequestMapping("/addOrderPhoDataByPE.shtml")
	@ResponseBody
	public ResultMap addOrderPhoDataByPE(HttpServletRequest request,
			HttpServletResponse response,OrderPhoVO orderPhoVO,String oLocation) {
		try{
			
			HttpSession session=request.getSession();
			DTOdateSet.setUpdateInfo(orderPhoVO,session);
			orderPhoVO.setCreateBy(orderPhoVO.getUpdateBy());
			orderPhoVO.setUpdateBy(orderPhoVO.getUpdateBy());
			OrderDTO  od=new OrderDTO();
			od.setId(orderPhoVO.getoId());
			OrderDTO orderDTO =  orderService.queryOrderDetail(od);
			if(orderDTO == null || StringUtils.isBlank(oLocation)){
				resultMap.setStatus(STATUS.ERROR);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				resultMap.setMessage("OrderDTO is not exists");
				return resultMap;
			}
			UserInfoDTO userinfo = (UserInfoDTO)session.getAttribute("USER");
			String orderPhos=request.getParameter("orderPhos")+" ,";
			String orderPhosStatus=request.getParameter("orderPhosStatus")+" ,";
			//上传文件
			addOrderPhos(orderPhoVO, userinfo, orderPhos,orderPhosStatus);

			//修改订单所在地
			OrderByGaiZaoDTO  orderUpdate = new OrderByGaiZaoDTO();
			DTOdateSet.setUpdateInfo(orderUpdate,session);
			orderUpdate.setId(orderPhoVO.getoId());
			orderUpdate.setoLocation(oLocation);
			orderService.updateOrder(orderUpdate);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryProductOrderData error",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}

	public void addOrderPhos(OrderPhoVO orderPhoVO, UserInfoDTO userinfo,
			String orderPhos,String orderPhosStatus) throws SQLException, Exception {
		ProductOrderDataDTO productOrderDataDto=new ProductOrderDataDTO();
		productOrderDataDto.setpId(Integer.parseInt(orderPhoVO.getpId()));
		productOrderDataDto.setpType(orderPhoVO.getpType());
		String productOrderTjzl=productOrderDataService.queryProductOrderData(productOrderDataDto);
		List<OrderPhoVO> list=new ArrayList<OrderPhoVO>();
		for (int i = 0; i < productOrderTjzl.split(",").length; i++) {
			//初始化参数
			OrderPhoVO opv=new OrderPhoVO();
			opv.setuId(userinfo.getUserId());
			opv.setoType(orderPhoVO.getoType());
			opv.setpType(orderPhoVO.getpType());
			opv.setpId(orderPhoVO.getpId());
			opv.setoId(orderPhoVO.getoId());
			opv.setoPhoStatus((StringUtils.isBlank(orderPhosStatus.split(",")[i])||"04".equals(orderPhosStatus.split(",")[i].trim()))?"02":orderPhosStatus.split(",")[i]);
			opv.setoPhoType(productOrderTjzl.split(",")[i]);
			opv.setoPhoUri(orderPhos.split(",")[i]);
			opv.setCreateBy(orderPhoVO.getUpdateBy());
			opv.setUpdateBy(orderPhoVO.getUpdateBy());
			list.add(opv);
		}
		orderPhoVO.setoType(orderPhoVO.getoType());
		orderPhoVO.setpType(orderPhoVO.getpType());
		orderPhoService.addFpOrderPho(list, orderPhoVO);
	}
//	/**
//	 * 下载所有附件
//	 */
//	@RequestMapping("/downloadAllPho.shtml")
//	@ResponseBody
//	public ResultMap downloadAllPho(HttpServletRequest request,
//			HttpServletResponse response,OrderPhoVO orderPhoVO) {
//		try{
//			// 变量
//			FileInputStream fis = null;
//			byte[] buffer = new byte[1024];
//			File tempFile = null;
//			int len;
//			ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
//			// 查询出三件套
//			List<Map<String, Object>> queryOrderPho = orderPhoService.queryOrderPho(orderPhoVO);
//			// 判断有无附件
//			for (Map<String, Object> map : queryOrderPho) {
//				if(null != map.get("oPhoUri")){
//					tempFile = new File(fileBaseDir + (String) map.get("oPhoUri"));
//					fis = new FileInputStream(tempFile);   
//					out.putNextEntry(new ZipEntry(tempFile.getName()));   
//			        //读入需要下载的文件的内容，打包到zip文件   
//			        while((len = fis.read(buffer))>0) {   
//			        	out.write(buffer,0,len);    
//			        }   
//			        out.closeEntry();   
//			        fis.close();   
//				}
//			}
//			response.addHeader("Content-Disposition", "attachment;filename=" + new String("pho.zip".getBytes("utf-8")));
//			response.setContentType("application/octet-stream");
//			out.close();
//			resultMap.setStatus(STATUS.SUCCESS);
//			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
//		}catch(Exception e){
//			log.error("query proOrderDataDetail error",e);
//			resultMap.setStatus(STATUS.FAILE);
//			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
//		}
//		return resultMap;
//	}
}
